import { Component, director, resources, SceneAsset } from 'cc';
import Instance from '../utils/Instance';

export interface ISceneMgr {
    /**
     * 预加载场景
     * @param name 场景名称
     * @param onProgress 加载进度回调
     * @returns 预加载完成的 Promise
     */
    preloadScene(name: string, onProgress?: (count: number, total: number, item: any) => void): Promise<void>;

    /**
     * 加载场景
     * @param name 场景名称
     * @returns 加载完成的 Promise
     */
    loadScene(name: string): Promise<void>;

    /**
     * 直接加载场景而不预加载
     * @param name 场景名称
     * @returns 加载完成的 Promise
     */
    loadSceneWithoutPreload(name: string): Promise<void>;
}

export class SceneMgr implements ISceneMgr {
    public static getInstance(): SceneMgr {
        return Instance.get<SceneMgr>(SceneMgr);
    }

    async preloadScene(name: string, onProgress?: (count: number, total: number, item: any) => void): Promise<void> {
        return new Promise((resolve, reject) => {
            resources.preloadScene(name, onProgress, (err: Error | null) => {
                //`场景${name}加载失败`
                if (err) return reject(err);
                //`场景${name}加载成功`
                return resolve();
            });
        });
    }

    async loadScene(name: string): Promise<void> {
        return new Promise((resolve, reject) => {
            resources.loadScene(name, (err: Error | null, scene: SceneAsset) => {
                if (err) return reject(err);
                director.runScene(scene);
                return resolve();
            });
        });
    }

    async loadSceneWithoutPreload(name: string): Promise<void> {
        return new Promise((resolve, reject) => {
            resources.loadScene(name, (err: Error | null, scene: SceneAsset) => {
                if (err) return reject(err);
                director.runScene(scene);
                return resolve();
            });
        });
    }
}
